package com.wgts.wgts.tools;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wgts.wgts.MoHuApplication;
import com.wgts.wgts.R;
import com.wgts.wgts.control.dialog.ToastDate;
import com.wgts.wgts.control.dialog.ToastDialogFragment;
import com.wgts.wgts.control.progress.DownLoadProgressbar;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.netmodle.AppOkHttpClient;
import com.wgts.wgts.netmodle.DownloadFile;
import com.wgts.wgts.netmodle.resp.AppUpdateEntity;
import com.hjq.permissions.XXPermissions;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;

import java.text.NumberFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/*
 *
 *
 *   data:2018/9/1111:31
 *
 */

@RuntimePermissions
public class UpdateDialogFragment extends DialogFragment {
    @BindView(R.id.cancel_question_tv)
    TextView cancelQuestionTv;
    @BindView(R.id.order_cancel_tv)
    TextView orderCancelTv;
    @BindView(R.id.order_cancel_ly)
    LinearLayout orderCancelLy;
    @BindView(R.id.point_error_tv)
    TextView pointErrorTv;
    @BindView(R.id.point_error_ly)
    LinearLayout pointErrorLy;
    Unbinder unbinder;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.tv_progress)
    TextView tvProgress;
    private View view;
    private static final String Sbundle = "ToastMessage";
    private AppUpdateEntity date;

    private OnClickListener onClickListener;

    public static InstallUtil mInstallUtil;

    public static void setmInstallUtil(InstallUtil mInstallUtil) {
        UpdateDialogFragment.mInstallUtil = mInstallUtil;
    }

    @Override
    public void onStart() {
        super.onStart();
        // 设置宽度为屏宽, 靠近屏幕底部。
        Window win = getDialog().getWindow();
        // 一定要设置Background，如果不设置，window属性设置无效
        win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);

        WindowManager.LayoutParams params = win.getAttributes();
        params.gravity = Gravity.CENTER;

        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        win.setAttributes(params);
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        Dialog alertDialog = new Dialog(getContext());
        alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        View customView = onCreateDialogView();
        alertDialog.setContentView(customView);
        alertDialog.setCanceledOnTouchOutside(false);

        alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });

        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams windowParams = alertDialog.getWindow().getAttributes();
        windowParams.width = (int) (getResources().getDisplayMetrics().widthPixels -
                getResources().getDisplayMetrics().density * 20);
        alertDialog.getWindow().setAttributes(windowParams);

        return alertDialog;
    }

    public View onCreateDialogView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            date = bundle.getParcelable(Sbundle);
        }
        view = LayoutInflater.from(getContext()).inflate(R.layout.update_dialog_fragment_toast, null);
        unbinder = ButterKnife.bind(this, view);


        cancelQuestionTv.setText(date.upgradeLog);
        orderCancelTv.setText("立即升级");
        pointErrorTv.setText("取消");
        if (date.forceUpgrade == 1) {
            pointErrorLy.setVisibility(View.GONE);
            line.setVisibility(View.GONE);

        }else {
            pointErrorLy.setVisibility(View.VISIBLE);
            line.setVisibility(View.VISIBLE);
        }

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.order_cancel_ly, R.id.point_error_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.order_cancel_ly:

                UpdateDialogFragmentPermissionsDispatcher.needPermissionWithPermissionCheck(this);

                break;
            case R.id.point_error_ly:
                dismiss();
                break;
        }
    }

    public static UpdateDialogFragment setToastMessage(AppUpdateEntity date) {
        UpdateDialogFragment fragment = new UpdateDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable(Sbundle, date);
        fragment.setArguments(bundle);
        return fragment;
    }



    public interface OnClickListener {
        void onClickCancle();

        void onClickEnsuer();
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    NumberFormat numberFormat = NumberFormat.getInstance();

    private void onClickEnsure() {
        orderCancelLy.setEnabled(false);
        if (date.forceUpgrade == 0) {
            dismiss();
        }
        DownloadFile downloadFile = new DownloadFile(AppOkHttpClient.getInstance().getOkHttpClient());
        downloadFile.downLoad(date.url, new FileDownloadLargeFileListener() {
            @Override
            protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                if(tvProgress != null){
                    tvProgress.setVisibility(View.VISIBLE);
                    tvProgress.setText("等待下载");
                    orderCancelLy.setEnabled(false);
                }
            }

            @Override
            protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                if(tvProgress != null){
                    tvProgress.setText("下载进度" + "   " + String.valueOf(soFarBytes * 100 / totalBytes) + "%");
                }
            }

            @Override
            protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {

            }

            @Override
            protected void completed(BaseDownloadTask task) {
                mInstallUtil.install();
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                if(tvProgress != null){
                    tvProgress.setText("下载错误");
                }
            }

            @Override
            protected void warn(BaseDownloadTask task) {
                //mInstallUtil.install();
            }
        });
    }


    @NeedsPermission({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.READ_EXTERNAL_STORAGE})
    public void needPermission() {
        onClickEnsure();
    }

    @OnNeverAskAgain({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.READ_EXTERNAL_STORAGE})
    public void openPermission() {
        MoHuToast.showToast("拒绝权限部分功能将不能使用，请去设置打开权限");

        ToastDate toastDate = new ToastDate();
        toastDate.setCancelQuestion("拒绝权限部分功能将不能使用，请去设置打开权限");
        toastDate.setCancelText("去设置");
        toastDate.setPointText("取消");
        toastDate.setFragmentManager(getChildFragmentManager());
        ToastDialogFragment fragment = ToastDialogFragment.setToastMessage(toastDate);
        fragment.show(getChildFragmentManager(), "");
        fragment.setOnClickListener(new ToastDialogFragment.OnClickListener() {
            @Override
            public void onClickCancle() {
                MoHuToast.showToast("您已拒绝了相应权限，无法更新应用");
            }

            @Override
            public void onClickEnsuer() {

                XXPermissions.gotoPermissionSettings(getContext());
            }
        });

    }

    @OnPermissionDenied({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.READ_EXTERNAL_STORAGE})
    public void deniedPermission() {
        MoHuToast.showToast("拒绝权限部分功能将不能使用，请去设置打开权限");

        ToastDate toastDate = new ToastDate();
        toastDate.setCancelQuestion("拒绝权限部分功能将不能使用，请去设置打开权限");
        toastDate.setCancelText("去设置");
        toastDate.setPointText("取消");
        toastDate.setFragmentManager(getChildFragmentManager());
        ToastDialogFragment fragment = ToastDialogFragment.setToastMessage(toastDate);
        fragment.show(getChildFragmentManager(), "");
        fragment.setOnClickListener(new ToastDialogFragment.OnClickListener() {
            @Override
            public void onClickCancle() {
                MoHuToast.showToast("您已拒绝了相应权限，无法更新应用");
            }

            @Override
            public void onClickEnsuer() {

                XXPermissions.gotoPermissionSettings(getContext());
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UpdateDialogFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


}
